package org.ovgu.coursify;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.ovgu.coursify.data.Comment;
import org.ovgu.coursify.data.DataBase;

import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.ActionBar.TabListener;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.support.v13.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.PopupMenu.OnMenuItemClickListener;

public class ViewComments extends Activity {

	/**
	 * The {@link android.support.v4.view.PagerAdapter} that will provide
	 * fragments for each of the sections. We use a {@link FragmentPagerAdapter}
	 * derivative, which will keep every loaded fragment in memory. If this
	 * becomes too memory intensive, it may be best to switch to a
	 * {@link android.support.v13.app.FragmentStatePagerAdapter}.
	 */
	private SectionsPagerAdapter mSectionsPagerAdapter;

	/**
	 * The {@link ViewPager} that will host the section contents.
	 */
	private ViewPager mViewPager;
	private static ViewComments viewComments;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		viewComments = this;
		setContentView(R.layout.activity_view_comments);

		setTitle(DataBase.getLection(HomeActivity.SELECTEDCOURSE).getName());
		mSectionsPagerAdapter = new SectionsPagerAdapter(getFragmentManager());

		mViewPager = (ViewPager) findViewById(R.id.pager);
		mViewPager.setAdapter(mSectionsPagerAdapter);

		final ActionBar actionBar = getActionBar();
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

		TabListener tabListener = new TabListener() {

			@Override
			public void onTabUnselected(Tab tab, FragmentTransaction ft) {
			}

			@Override
			public void onTabSelected(Tab tab, FragmentTransaction ft) {
				mViewPager.setCurrentItem(tab.getPosition());
			}

			@Override
			public void onTabReselected(Tab tab, FragmentTransaction ft) {
			}
		};

		for (int i = 0; i < getCount(); i++) {
			actionBar.addTab(actionBar.newTab().setText("Page " + (i + 1))
					.setTabListener(tabListener));
		}

		mViewPager
				.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
					@Override
					public void onPageSelected(int position) {
						getActionBar().setSelectedNavigationItem(position);
					}
				});

	}

	public void backToHome(int id) {
		Intent ide = new Intent(ViewComments.this, HomeActivity.class);
		ide.putExtra("org.ovgu.coursify.HomeActivity", "HOME");
		ide.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		startActivity(ide);
	}

	public void backToComment(int id) {
		Intent ide = new Intent(ViewComments.this, CommentAndRateActivity.class);
		ide.putExtra("org.ovgu.coursify.CommentAndRate", "COMMENT");
		ide.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		startActivity(ide);
	}

	/**
	 * Gets count of the total number of comment pages. The count is limited to
	 * max 5. The older comments won't be shown.
	 */
	public int getCount() {
		int allComments = DataBase.getComments(HomeActivity.SELECTEDCOURSE)
				.size();
		int pages = allComments / 5;
		if (pages * 5 > allComments)
			pages++;
		else if (allComments > 0) {
			pages++;
		}
		return pages > 5 ? 5 : pages;
	}

	public class SectionsPagerAdapter extends FragmentPagerAdapter {

		public SectionsPagerAdapter(FragmentManager fragmentManager) {
			super(fragmentManager);
		}

		@Override
		public Fragment getItem(int position) {
			return PlaceholderFragment.newInstance(position,
					HomeActivity.SELECTEDCOURSE);
		}

		@Override
		public int getCount() {
			return ViewComments.this.getCount();
		}

		@Override
		public CharSequence getPageTitle(int position) {
			return "Page " + Integer.toString(position + 1);
		}
	}

	public static class PlaceholderFragment extends Fragment {

		public static PlaceholderFragment newInstance(int pageNumber,
				int lection) {

			PlaceholderFragment fragment = new PlaceholderFragment();

			Bundle bundle = new Bundle();
			bundle.putInt("page", pageNumber);
			fragment.setArguments(bundle);
			return fragment;
		}

		private CommentAdapter getAdapter(int page) {
			List<Comment> comments = DataBase
					.getComments(HomeActivity.SELECTEDCOURSE);
			List<Comment> commentsInPage = new ArrayList<Comment>();
			for (int i = page * 5; i < page * 5 + 5; i++) {
				if (i > comments.size() - 1)
					break;
				commentsInPage.add(comments.get(i));
			}
			Collections.reverse(commentsInPage);
			return new CommentAdapter(HomeActivity.getContext(),
					R.layout.comment_layout, commentsInPage);
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			View rootView = inflater.inflate(R.layout.fragment_view_comments,
					container, false);

			int page = getArguments().getInt("page");

			ListView pager = (ListView) rootView
					.findViewById(R.id.commentsListView);

			pager.setAdapter(getAdapter(page));
			Button back = (Button) rootView.findViewById(R.id.buttonBack);

			final PopupMenu menu = new PopupMenu(HomeActivity.getContext(),
					back);
			menu.getMenu().add("Back to home");
			menu.getMenu().add("Back to Comment and Rate");

			menu.setOnMenuItemClickListener(new OnMenuItemClickListener() {

				@Override
				public boolean onMenuItemClick(MenuItem item) {
					if (item.getTitle().equals("Back to home")) {
						viewComments.backToHome(R.layout.activity_home);
					} else if (item.getTitle().equals(
							"Back to Comment and Rate")) {
						viewComments
								.backToHome(R.layout.activity_comment_and_rate);
					}
					viewComments.finish();
					return false;
				}
			});

			// registerForContextMenu(back);
			back.setOnLongClickListener(new OnLongClickListener() {

				@Override
				public boolean onLongClick(View v) {

					menu.show();
					return true;
				}
			});

			return rootView;
		}
	}
}
